package com.bw.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.SysUser;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2024年01月23日 10:51
 */

@RestController
@RequestMapping("auth")
public class AuthController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SysUserService sysUserService;


    @RequestMapping("login")
    public Result login(@RequestBody SysUser sysUser) {

        String redisCode = (String) redisTemplate.opsForValue().get(sysUser.getUid());
        if (!sysUser.getCode().equals(redisCode)) {
            return Result.fail("验证码错误");
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, sysUser.getUsername());
        SysUser dbUser = sysUserService.getOne(wrapper);
        if(null ==dbUser){
            return Result.fail("用户不存在");
        }
        if(!dbUser.getPassword().equals(sysUser.getPassword())){
            return Result.fail("密码错误");
        }
        String token = JWTUtils.createToken(dbUser.getId(), 3 * 60);
        return Result.success(token);

    }


    @RequestMapping("createCode")
    public void createCode(String uid, HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uid, captcha.getCode(), 5, TimeUnit.MINUTES);
    }
}
